package edu.zhuoxun.blogserver.controller;

import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

@Controller
public class UploadImageController {
    @Autowired
    public String imagePath;
    @PostMapping("api/uploadImage")
    @ResponseBody
    public String uploadImage(MultipartFile file) {
        File folder = new File(imagePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File f = new File(folder, UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().length() - 4));
        try {
            file.transferTo(f);
            return "http://localhost:8085/api/image/" + f.getName();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    @GetMapping("api/image/load")
    public void loadImage(String url, HttpServletResponse response){
        URLConnection connection;
        try {
            url = url.substring(0, url.indexOf('?'));
            connection = new URL(url).openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
            String contentType = connection.getContentType();
            response.setHeader("content-type", contentType);
            InputStream is = connection.getInputStream();
            ServletOutputStream os = response.getOutputStream();
            int length;
            byte[] buffer = new byte[1 << 20];
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

//        response.getOutputStream().write();
    }
}
